<?php

namespace App\Http\Middleware;

use App\Repositories\Permission\PermissionRepository;
use Closure;
use Illuminate\Http\Request;
use Inertia\Inertia;

class AdminIsValid
{
    public function handle(Request $request, Closure $next)
    {
        if (auth('admin')->guest()) {
            return redirect()->route('admin.login');
        }

        $admin = $request->user('admin');

        if ($admin->is_super) {
            $admin_permissions = app(PermissionRepository::class)->getPermissions();
        }else{
            $admin_permissions = $admin->getMenuTree();
        }

//        $admin_permissions = [];
//        if (empty($admin_permissions)) {
//            abort(401);
//            return redirect()->route('errors.404');
//        }

        Inertia::share([
            'auth' => [
                'name' => $admin->name,
                'phone' => $admin->phone,
                'email' => $admin->email,
                'avatar' => $admin->avatar,
            ],
            'permission_menus' => $admin_permissions
        ]);
        return $next($request);
    }
}
